//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only


import React, { useEffect, useState } from 'react';
import { useStores } from '@/hooks';
import { request } from '@/utils/request';
import type { MemoInfo } from "@/api/user_memo";
import { get_memo, list_memo, list_tag, remove_memo } from "@/api/user_memo";
import { Button, Card, List, message, Modal, Popover, Space } from 'antd';
import { ReadOnlyEditor } from '@/components/Editor';
import { EditOutlined, ExportOutlined, MoreOutlined } from '@ant-design/icons';
import EditMemoModal from './EditMemoModal';
import moment from 'moment';
import { appWindow, WebviewWindow } from '@tauri-apps/api/window';
import type * as NoticeType from '@/api/notice_type';
import { listen } from '@tauri-apps/api/event';
import { sleep } from '@/utils/time';
import { runInAction } from 'mobx';
import { observer, useLocalObservable } from 'mobx-react';


const PAGE_SIZE = 12;

export interface MemoListProps {
    curMemoTagList: string[];
    dataVersion: number;
    onLoadTagList: (newTagList: string[]) => void;
}

const MemoList = (props: MemoListProps) => {
    const userStore = useStores("userStore");

    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [allTagList, setAllTagList] = useState<string[]>([]);

    const [editMemoInfo, setEditMemoInfo] = useState<MemoInfo | null>(null);
    const [removeMemoInfo, setRemoveMemoInfo] = useState<MemoInfo | null>(null);


    const localStore = useLocalObservable(() => ({
        memoList: [] as MemoInfo[],
        setMemoList(infoList: MemoInfo[]) {
            runInAction(() => {
                this.memoList = infoList;
            });
        },
    }));

    const loadTagList = async () => {
        const res = await request(list_tag({
            session_id: userStore.sessionId,
        }));
        props.onLoadTagList(res.tag_list);
        setAllTagList(res.tag_list);
    };

    const loadMemoList = async () => {
        const res = await request(list_memo({
            session_id: userStore.sessionId,
            filter_by_tag: props.curMemoTagList.length > 0,
            tag_list: props.curMemoTagList,
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setTotalCount(res.total_count);
        localStore.setMemoList(res.memo_list);
    };

    const loadMemoInfo = async (memoId: string) => {
        const tmpList: MemoInfo[] = localStore.memoList.slice();

        const index = tmpList.findIndex(item => item.memo_id == memoId);
        if (index == -1) {
            return;
        }
        await sleep(100);
        const res = await request(get_memo({
            session_id: userStore.sessionId,
            memo_id: memoId,
        }));
        tmpList[index] = res.memo;
        localStore.setMemoList(tmpList);
    }

    const onUpdate = async () => {
        if (editMemoInfo == null) {
            return;
        }
        const tmpList = localStore.memoList.slice();
        const index = tmpList.findIndex(item => item.memo_id == editMemoInfo.memo_id);
        if (index == -1) {
            return;
        }
        const res = await request(get_memo({
            session_id: userStore.sessionId,
            memo_id: editMemoInfo.memo_id,
        }));
        tmpList[index] = res.memo;
        localStore.setMemoList(tmpList);
        await loadTagList();
        setEditMemoInfo(null);
    };

    const removeMemo = async () => {
        if (removeMemoInfo == null) {
            return;
        }
        await request(remove_memo({
            session_id: userStore.sessionId,
            memo_id: removeMemoInfo.memo_id,
        }));
        message.info("删除成功");
        await loadMemoList();
        await loadTagList();
        setRemoveMemoInfo(null);
    };

    const openWindow = async (memoId: string) => {
        const label = `usermemo:${memoId.replaceAll("-", "")}`;
        const view = WebviewWindow.getByLabel(label);
        if (view != null) {
            await view.close();
        }
        const pos = await appWindow.innerPosition();
        new WebviewWindow(label, {
            url: `user_memo.html?id=${encodeURIComponent(memoId)}&fsId=${encodeURIComponent(userStore.userInfo.userMemoFsId)}`,
            x: pos.x + Math.floor(Math.random() * 500),
            y: pos.y + Math.floor(Math.random() * 200),
            width: 300,
            height: 260,
            decorations: false,
            alwaysOnTop: true,
            skipTaskbar: true,
            fileDropEnabled: false,
            transparent: true,
            resizable: false,
        });
    }

    useEffect(() => {
        loadTagList();
    }, [props.dataVersion]);

    useEffect(() => {
        if (curPage != 0) {
            setCurPage(0);
        } else {
            loadMemoList();
        }
    }, [props.dataVersion, props.curMemoTagList]);

    useEffect(() => {
        loadMemoList();
    }, [curPage]);


    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.ClientNotice?.UpdateUserMemoNotice != undefined) {
                loadMemoInfo(notice.ClientNotice.UpdateUserMemoNotice.memoId);
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, []);

    return (
        <>
            <List rowKey="memo_id" dataSource={localStore.memoList} grid={{ gutter: 16 }} style={{ paddingTop: "10px" }}
                pagination={{ current: curPage + 1, total: totalCount, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), hideOnSinglePage: false, showSizeChanger: false }}
                renderItem={item => (
                    <List.Item>
                        <Card title={`${moment(item.update_time).format("YYYY-MM-DD HH:mm")}  标签:${item.basic_info.tag_list.join(",")}`}
                            style={{ width: "300px", backgroundColor: item.basic_info.bg_color, borderRadius: "10px", boxShadow: "10px 10px 10px 0px #777" }}
                            bodyStyle={{ height: "220px" }} bordered={false} headStyle={{ border: "none" }}
                            extra={
                                <Space>
                                    <Button type="link" icon={<ExportOutlined />} style={{ minWidth: 0, padding: "0px 0px" }} title='浮动显示'
                                        onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            openWindow(item.memo_id);
                                        }} />
                                    <Button type='text' icon={<EditOutlined />} style={{ minWidth: 0, padding: "0px 0px" }} title='编辑'
                                        onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setEditMemoInfo(item);
                                        }} />
                                    <Popover trigger="click" placement="bottom" content={
                                        <Space direction="vertical">
                                            <Button type="link" danger onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setRemoveMemoInfo(item);
                                            }}>删除</Button>
                                        </Space>
                                    }>
                                        <MoreOutlined />
                                    </Popover>
                                </Space>
                            }>
                            <div className="_commentContext">
                                <ReadOnlyEditor content={item.basic_info.content} />
                            </div>
                        </Card>
                    </List.Item>
                )} />
            {editMemoInfo != null && (
                <EditMemoModal memoInfo={editMemoInfo} tagList={allTagList} onCancel={() => setEditMemoInfo(null)}
                    onOk={() => onUpdate()} />
            )}
            {removeMemoInfo != null && (
                <Modal open title="删除备忘录" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveMemoInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeMemo();
                    }}>
                    是否删除当前备忘录?
                </Modal>
            )}
        </>
    );
};

export default observer(MemoList);